import logging
from typing import Optional

from fastapi import APIRouter, Query, Depends, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme

equipment_class_router = APIRouter(prefix="/equipment/equipmentClass", tags=["设备分类管理"],
                                   dependencies=[Depends(oauth2_scheme)])


class EquipmentClassSearch(PaginationBase):
    fclassstname: str = Field(None, description="分类名")
    fparentno: str = Field(None, description="上级分类名")


@equipment_class_router.get("/list", summary="查询设备分类")
def list_equipment_classes(equipment: EquipmentClassSearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from s_ts_equipment_class where 1=1"
    if equipment.fclassstname is not None:
        sql = sql + " and fclassstname like concat('%', :fclassstname ,'%') "
        param["fclassstname"] = equipment.fclassstname
    if equipment.fparentno is not None:
        sql = sql + " and fparentno = :fparentno "
        param["fparentno"] = equipment.fparentno
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fclassstno,fclassstname,fparentno,fclassstyle,flevel,fdiscmonth,fupddate,foperator"
    sql = sql + " from s_ts_equipment_class where 1=1"
    if equipment.fclassstname is not None:
        sql = sql + " and fclassstname like concat('%', :fclassstname ,'%') "
        param["fclassstname"] = equipment.fclassstname
    if equipment.fparentno is not None:
        sql = sql + " and fparentno = :fparentno "
        param["fparentno"] = equipment.fparentno
    sql = sql + " limit :limit offset :offset"
    param["offset"] = equipment.offset
    param["limit"] = equipment.limit
    data = db.execute(text(sql), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fclassstno'] = data[key][0]
        d1['fclassstname'] = data[key][1]
        d1['fparentno'] = data[key][2]
        d1['fclassstyle'] = data[key][3]
        d1['flevel'] = data[key][4]
        d1['fdiscmonth'] = data[key][5]
        d1['fupddate'] = data[key][6]
        d1['foperator'] = data[key][7]
        data_list.append(d1)

    info_dict = {"list": data_list,
                 "total": count,
                 "page": equipment.pageIndex,
                 "pages": (count + equipment.limit - 1) // equipment.limit,
                 "limit": equipment.limit}
    return BaseResponse.success(data=info_dict)


class EquipmentClassCreate(BaseModel):
    """设备分类创建模型"""
    fclassstno: str = Field(..., description="设备分类编号", min_length=1, max_length=50)
    fclassstname: str = Field(..., description="设备分类名称", min_length=1, max_length=100)
    foperator: str = Field(..., description="操作人", min_length=1, max_length=20)
    fupddate: str = Field(..., description="更新日期", max_length=10)
    fparentno: Optional[str] = Field("", description="父分类编号", max_length=50)


@equipment_class_router.post("/create", summary="创建设备分类")
def create_equipment_class(equipment: EquipmentClassCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select fclassstno from s_ts_equipment_class where fclassstno= :fclassstno "
            data = db.execute(text(sql), {
                "fclassstno": equipment.fclassstno,
            }).fetchall()

            if len(data) > 0:
                return BaseResponse.error(message="编号已存在")
            else:
                sql = "insert into s_ts_equipment_class(fclassstno,fclassstname,fparentno,fclassstyle,flevel,fdiscmonth,fupddate,foperator)"
                sql = sql + " values( :fclassstno , :fclassstname , :fparentno ,0,1,0, :fupddate , :foperator );"
                db.execute(text(sql), {
                    "fclassstno": equipment.fclassstno,
                    "fclassstname": equipment.fclassstname,
                    "fparentno": equipment.fparentno,
                    "fupddate": equipment.fupddate,
                    "foperator": equipment.foperator,
                })
                # 返回
                d1 = {}
                d1["fclassstname"] = equipment.fclassstname
                d1["fclassstno"] = equipment.fclassstno
                d1["fclassstyle"] = None
                d1["fdiscmonth"] = 0
                d1["flevel"] = 1
                d1["foperator"] = equipment.foperator
                d1["fparentno"] = equipment.fparentno
                d1["fupddate"] = equipment.fupddate
                return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@equipment_class_router.post("/update", summary="更新设备分类")
def update_equipment_class(equipment: EquipmentClassCreate, db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "update s_ts_equipment_class"
            sql = sql + " set fclassstname= :fclassstname ,fparentno= :fparentno "
            sql = sql + " ,fupddate= :fupddate ,foperator= :foperator "
            sql = sql + " where fclassstno= :fclassstno "
            db.execute(text(sql), {
                "fclassstname": equipment.fclassstname,
                "fparentno": equipment.fparentno,
                "fupddate": equipment.fupddate,
                "foperator": equipment.foperator,
                "fclassstno": equipment.fclassstno,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@equipment_class_router.post("/delete/{fclassstno}", summary="删除设备分类")
def delete_equipment_class(fclassstno: str = Path(description="分类编号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select count(1) from s_ts_equipment_info where fclassstno= :fclassstno "
            data = db.execute(text(sql), {
                "fclassstno": fclassstno,
            }).scalar()

            if data > 0:
                return BaseResponse.error(message="该资料在使用，不能删除")
            else:
                sql = "delete from s_ts_equipment_class where fclassstno= :fclassstno "
                db.execute(text(sql), {
                    "fclassstno": fclassstno
                })
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
